<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
class PurchaseWarehousinglogic{
	/**
     * 采购入库列表
     * @param int 	 $user_id  操作用户ID
	 * @param string handled_by	经办人
	 * @param string code   	采购单号
     * @author shiqiang
     * @return mixed
     */
    public function list($user_id, $handled_by = '', $code = ''){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 			=> $user_id,
				'handled_by' 		=> $handled_by,
				'code' 				=> $code,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/

            $map = [];//搜索处理
            if($handled_by != '') 	$map[] = ['handled_by', 'like', '%'. $handled_by .'%'];
			if($code != '') 		$map[] = ['code', 'like', '%'. $code .'%'];
			$map[] = ['type', '=', 1];//采购入库 
			$list = model('ErpGoodsWarehousing', 'model') -> where($map) -> order('create_time desc') -> paginate();
			$rel_list = [];
            foreach($list as $key => $value){
				$rel_list[$key]['id'] 			= (int)$value['id'];
				$rel_list[$key]['type'] 		= (int)$value['type'];
				$rel_list[$key]['handledBy'] 	= (string)$value['handled_by'];	//经办人
				$rel_list[$key]['remark'] 		= (string)$value['remark'];
				$rel_list[$key]['code'] 		= (string)$value['code'];
				$rel_list[$key]['createTime'] 	= (int)$value['create_time'];
				
				
				$order_code = model('ErpGoodsPurchaseOrder', 'model') -> find($value['order_id']);
				$rel_list[$key]['purchaseOrder'] = [
					'id' 				=> (int)$order_code['id'],
					'title' 			=> (string)$order_code['title'],
					'supplier' 			=> (string)$order_code['get_erp_supplier']['title'], //供应商
					'procurementMethod' => (string)$order_code['procurement_method'] == 1 ? '现购' : '赊购',
					'arrivalWarehouse' 	=> (string)$order_code['get_erp_warehouse']['title'],	//仓库
					'advanceCharge' 	=> (string)$order_code['advance_charge'],				//预付款
					'arrivalDays' 		=> (int)$order_code['arrival_days'],					//到货天数
					'remark' 			=> (string)$order_code['remark'],						//备注
					'handledBy' 		=> (string)$order_code['handled_by'], 					//经办人
					'code' 				=> (string)$order_code['code'],
					'status' 			=> (int)$order_code['purchase_status'],
					'createTime'		=> (int)$order_code['create_time'],
				];
			}
			$result_list = [];
			$result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
			$result_list['data'] 			= $rel_list;
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 采购入库
	 * @param int  		user_id				
	 * @param string  	order_id			 采购单id	
	 * @param string 	handled_by			 经办人
	 * @param string 	remark		 		 备注
	 * @param array 	order_sku		 	 采购sku
	 * @param int 		purchase_sku_id		 采购单sku_id
	 * @param int 		sku_id		 		 采购sku - 商品sku_id
	 * @param int 		num		 		 	 采购sku - 实际数量
	 * @param string 	remark		 		 采购sku - 备注    
     * @author shiqiang
     * @return mixed
     */
	public function add($user_id, $order_id, $handled_by, $remark, $order_sku, $type = 1){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 				=> $user_id,
				'type' 					=> $type,
				'order_id' 				=> $order_id,
				'handled_by' 			=> $handled_by,
				'remark' 				=> $remark,
				'order_sku' 			=> $order_sku,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$order_code = model('ErpGoodsPurchaseOrder', 'model') -> find($order_id);
			if(empty($order_code) || $order_code['purchase_status'] != 1){
				DB::rollback();
				return array_out(-1005, 'error1'); // 不存在采购单
			}
			
			$code 			= $order_code['code'];
			$warehouse_id 	= $order_code['arrival_warehouse_id'];//仓库id
			$rel = model('ErpGoodsWarehousing', 'model') -> addData($type, $order_id, $handled_by, $remark, $code);
			if($rel['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error'); // 插入失败
			}
			
			//插入采购单 实际采购书 sku参数
			$sku_arr = [];
			foreach($order_sku as $key => $value){
				$sku_arr[] = [
					'id' 		=> $value['purchase_sku_id'],
					'sku_id' 	=> $value['sku_id'],
					'rk_num'	=> $value['num'],
					'remark'	=> $value['remark'],
				];
			}
			$rel = model('ErpGoodsPurchaseOrderSku') -> saveAll($sku_arr);//dump($rel);
			if(!$rel < 0){
				DB::rollback();
				return array_out(-1005, 'error2');
			}
			
			foreach($sku_arr as $key => $value){
				//计算库存
				$map = [];
				$map['warehouse_id'] = $warehouse_id;
				$map['sku_id'] 		 = $value['sku_id'];
				$warehouse_num = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();//获取仓库数量
				
				if(empty($warehouse_num)){//插入库存
					$sku_info = model('ErpGoodsSku') -> where('id', $value['sku_id']) -> find();//商品sku - 获取价格
					$rel = model('ErpGoodsWarehouseStockNum') -> addData($warehouse_id, $value['sku_id'], $value['rk_num'], $value['rk_num'], $sku_info['goods_id'], $sku_info['price']);
				}else{//更新库存
					$stock_num 		= $warehouse_num['stock_num'] + $value['rk_num'];//总库存
					$available_num  = $stock_num - $warehouse_num['frozen_num'];//可用库存
					$rel = model('ErpGoodsWarehouseStockNum') -> editData($warehouse_num['id'], $warehouse_id, $value['sku_id'], $stock_num, '', $available_num);
				}
				if($rel['code'] < 0){
					DB::rollback();
					return array_out(-1005, 'error3');//更新库存失败
				}
			}
			
			$map = [];
			$map['id'] = $order_id;
			$data = [];
			$data['purchase_status'] = 2;
			$res = model('ErpGoodsPurchaseOrder') ->update($data, $map);//更新采购单状态
			if($rel['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error4');//更新库存失败
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    } 
	
	/**
     * 采购单详情
     * @param int 	 $user_id  操作用户ID
     * @author shiqiang
     * @return mixed
     */
    public function details($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$info = model('ErpGoodsWarehousing', 'model') -> find($id);
			$rel_list = [];
			if(!empty($info)){
				$rel_list['id'] 			= (int)$info['id'];
				$rel_list['type'] 		= (int)$info['type'];
				$rel_list['handledBy'] 	= (string)$info['handled_by'];	//经办人
				$rel_list['remark'] 		= (string)$info['remark'];
				$rel_list['code'] 		= (string)$info['code'];
				$rel_list['createTime'] 	= (int)$info['create_time'];
				
				
				$order_code = model('ErpGoodsPurchaseOrder', 'model') -> find($info['order_id']);
				$rel_list['purchaseOrder'] = [
					'id' 				=> (int)$order_code['id'],
					'title' 			=> (string)$order_code['title'],
					'supplier' 			=> (string)$order_code['get_erp_supplier']['title'], //供应商
					'procurementMethod' => (string)$order_code['procurement_method'] == 1 ? '现购' : '赊购',
					'arrivalWarehouse' 	=> (string)$order_code['get_erp_warehouse']['title'],	//仓库
					'advanceCharge' 	=> (string)$order_code['advance_charge'],				//预付款
					'arrivalDays' 		=> (int)$order_code['arrival_days'],					//到货天数
					'remark' 			=> (string)$order_code['remark'],						//备注
					'handledBy' 		=> (string)$order_code['handled_by'], 					//经办人
					'code' 				=> (string)$order_code['code'],
					'status' 			=> (int)$order_code['purchase_status'],
					'createTime'		=> (int)$order_code['create_time'],
				];
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}